package top.fengyulou.xiaofeng.common;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户工具
 */
public class UserUtils {
    //获取登录用户
    //获取登录用户id
    //验证用户是否登录
    //用户登录
    //退出登录

    /**
     * 当前登录用户
     */
    public static final String UID = "uid";

    /**
     * 获取登录用户
     *
     * @return
     */
    public static JSONObject getUser(HttpServletRequest request) {
        String json = (String) request.getSession().getAttribute(UID);
        if (StringUtils.isNotBlank(json)) {
            return JSONObject.parseObject(json);
        }
        return null;
    }

    /**
     * 获取登录用户id
     *
     * @return
     */
    public static String getUserId(HttpServletRequest request) {
        JSONObject user = getUser(request);
        if (ObjectUtils.isNotEmpty(user)) {
            return user.getString("id");
        }
        return null;
    }

    /**
     * 验证用户是否登录
     *
     * @return
     */
    public static boolean isLogin(HttpServletRequest request) {
        //获取用户数据
        JSONObject user = getUser(request);
        if (ObjectUtils.isNotEmpty(user)) {
            return true;
        }
        return false;
    }

    /**
     * 用户登录
     */
    public static void login(HttpServletRequest request, Object user) {
        request.getSession().setAttribute(UID, JSONObject.toJSONString(user));
    }

    /**
     * 退出登录
     */
    public static void logout(HttpServletRequest request) {
        request.getSession().removeAttribute(UID);
    }
}
